package com.ccsoft.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    // 获取网络文件大小
    public static long getHttpFileContentLength(String url) {
        long ret = 0;
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = getHttpURLConnection(url);
            ret = httpURLConnection.getContentLength();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if( httpURLConnection != null )
                httpURLConnection.disconnect();
        }
        return ret;
    }

    // 分块下载 - 返回分块下载的连接对象
    public static HttpURLConnection getHttpURLConnection(String url,long startPos,long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载起始终止位置：{} - {}",startPos,endPos);

        // 最后一个文件块的结束位置是0，其他块的结束位置非0
        if( endPos != 0 )
            // 非末尾块
            httpURLConnection.setRequestProperty("RANGE","bytes=" + startPos + "-" + endPos);
        else
            // 最后一个文件块
            httpURLConnection.setRequestProperty("RANGE","bytes=" + startPos + "-");

        return httpURLConnection;
    }

    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        // 创建 url 连接
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection)httpUrl.openConnection();

        // 模拟浏览器设置请求参数
        httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1;WOW64) AppleWebKit/535.1 (KHTML,like Gecko) Chrome/14.0.835.163 Safari/535.1");
        return httpURLConnection;
    }

    /**
     * 2021年12月25日 12:35:43 chanchaw
     * 从 url 中获取文件名，从 http://www.xdfznh.club/qq.exe
     * 中截取返回文件名：qq.exe
     * @param url
     * @return
     */
    public static String getFileName(String url){
        int lastIndex = url.lastIndexOf("/");
        return url.substring(lastIndex + 1);
    }
}
